package com.feiyue.learning.advance.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

/**
 * UDP Server
 * @author  feiyue
 * @date  2020/4/18
 */
public class UDPServer {

    private static final int BUFFER_SIZE = 1024;

    public static void main(String[] args) throws IOException {
        new UDPServer().receive();
    }

    private void receive() throws IOException {
        DatagramChannel dChannel = DatagramChannel.open();
        dChannel.configureBlocking(false);

        // 绑定监听地址
        dChannel.bind(new InetSocketAddress("127.0.0.1", 80));
        System.out.println("UDP Server 启动完成");

        // 开启一个通道选择器，并注册通道
        Selector selector = Selector.open();
        dChannel.register(selector, SelectionKey.OP_READ);

        // 选择器就绪列表存在值
        while (selector.select() > 0) {
            Iterator<SelectionKey> iteratorKey = selector.selectedKeys().iterator();
            ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
            while (iteratorKey.hasNext()) {
                SelectionKey key = iteratorKey.next();
                if (key.channel() instanceof DatagramChannel) {
                    System.out.println(((DatagramChannel) key.channel()).getLocalAddress());
                }

                // 可读事件有数据到来
                if (key.isReadable()) {
                    SocketAddress client = dChannel.receive(buffer);
                    buffer.flip();
                    System.out.println(new String(buffer.array(), 0, buffer.limit()));
                    buffer.clear();
                }
            }
            iteratorKey.remove();
        }
        selector.close();
        dChannel.close();
    }
}
